<?php

namespace Modules\Api\Service;

use HiCommon\Repository\CollectRepository;
use HiCommon\Repository\GoodsProductRepository;
use HiCommon\Repository\MaintainShopRepository;
use HiCommon\Repository\VehicleModelRepository;
use HiCommon\Repository\OrderRepairstoreRepository;
use HiCommon\Repository\RepairstoreGoodsRepository;
use HiCommon\Repository\OrderRepairstoreGoodsRepository;
use HiCommon\Repository\ShopRepository;
use HiCommon\Service\CommonService;
use HiCommon\Service\PublicService;

class MaintainShopService
{
    /**
     * 获取分页数据（保养）
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_list($arr_input)
    {
        try {
            if (empty($arr_input['shop_id'])) {
                return hello_error('门店id不能为空');
            }
            if (empty($arr_input['vehicle_model_id'])) {
                return hello_error('车型id不能为空');
            }
            //获取汽车系列
            $vehicle_model_id = intval($arr_input['vehicle_model_id']);

            $vehicle_model_obj = VehicleModelRepository::get_one_by_where($vehicle_model_id, ['id', 'parentid']);
            $vehicle_model_pid = 0;
            if ($vehicle_model_obj->first()) {
                $vehicle_model = $vehicle_model_obj->toarray();
                $vehicle_model_pid = $vehicle_model['parentid'];//汽车型号的父及id（用于筛选）
            }

            $arr_option = [
                'where' => ['shop_id' => $arr_input['shop_id']],
                'with' => ['father_config', 'son_config', 'maintain_shop_goods', 'maintain_vehicle_model'],
            ];
            $data = MaintainShopRepository::get_all($arr_option, $vehicle_model_pid)->toArray();

            $item = [];
            foreach ($data as $key => $value) {
                $item[$value['maintain_config_pid']]['f_name'] = $value['father_config']['name'];
                $goods = [];
                $total_price = 0.00;
                foreach ($value['maintain_shop_goods'] as $k => $v) {
                    $goods[] = [
                        'goods_id' => $v['goods']['id'],
                        'goods_name' => $v['goods']['name'],
                        'product_id' => $v['product']['id'],
                        'product_specs' => $v['product']['specs']['name'],
                        'product_pic' => $v['product']['pic']['full_src'],
                        'product_price' => $v['product']['price'],
                        'product_num' => $v['num'],
                    ];
                    $total_price += $v['product']['price'] * $v['num'];
                }
                if ($goods) {
                    $item[$value['maintain_config_pid']]['son'][] = [
                        'shop_id' => $value['shop_id'],
                        'maintain_shop_id' => $value['id'],
                        //'name' => $value['son_config']['name'],
                        'name' => $value['custom_title'] ?? $value['son_config']['name'],
                        'explain' => $value['son_config']['explain'],
                        'total_price' => number_format_money($total_price),
                        'goods' => $goods
                    ];
                }
            }

            $list = array_values($item);

            return hello_success('成功', $list);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     *  选择保养后预生成订单（保养）
     *
     *  2019 12 09
     */
    public function order_preview($arr_input)
    {
        try {
            if (empty($arr_input['maintain_shop_id'])) {
                return hello_error('保养种类id不能为空');
            }
            $maintain_id = intval($arr_input['maintain_shop_id']);
            //查询
            $arr_option['with'] = ['maintain_shop_goods', 'son_config'];
            $res = MaintainShopRepository::get_one($maintain_id, $arr_option)->toarray();
            if ($res) {
                $arrInput = ['with' => ['area_name'], 'where' => ['id' => $res['shop_id']]/*, 'lon' => $arr_input['lon'], 'lat' => $arr_input['lat']*/];
                $shop_obj = ShopRepository::get_one($arrInput);//获取门店信息
                if ($shop_obj->first()) {
                    $coordinate = [
                        'start_longitude' => $arr_input['lon'],
                        'start_latitude' => $arr_input['lat'],
                        'end_longitude' => $shop_obj->longitude,
                        'end_latitude' => $shop_obj->latitude,
                    ];

                    //重新计算距离
                    $distance = CommonService::api_location_distance($coordinate);

                    $city = str_replace(',', '', $shop_obj->area_name['mername']);
                    $data['shop_name'] = $shop_obj->name;
                    $data['shop_type'] = $shop_obj->shop_type;
                    $data['shop_address'] = $city . $shop_obj->address;
                    $data['distance'] = $distance['state'] == 0 ? $distance['data']['en_default'] : '0.00 km';
                } else {
                    return hello_error('门店不存在');
                }

                $data['user_realname'] = $arr_input['user_realname'];
                $data['user_phone'] = $arr_input['user_phone'];
                $data['maintain_shop_id'] = $res['id'];
                $data['maintain_name'] = $res['son_config']['name'];
                foreach ($res['maintain_shop_goods'] as $key => $value) {
                    $data['pic'][] = $value['product']['pic']['full_src'];
                    $data['goods'][] = [
                        'goods_id' => $value['goods_id'],
                        'goods_name' => $value['goods']['name'],
                        'product_id' => $value['product']['id'],
                        'product_specs' => $value['product']['specs']['name'],
                        'product_pic' => $value['product']['pic']['full_src'],
                        'product_price' => $value['product']['price'],
                        'product_num' => $value['num']
                    ];
                    $data['total_price'] += $value['product']['price'] * $value['num'];
                }

                return hello_success('查询成功', $data);
            }

            return hello_error('查询失败');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 获取维修服务商品列表（服务）
     *
     * 2019 12 10
     */
    public function get_repair_goods_list($arr_input)
    {
        try {
            if (empty($arr_input['shop_id'])) {
                return hello_error('门店id不能为空');
            }
            $shop_id = intval($arr_input['shop_id']);
            $option = ['shop_id' => $shop_id, 'status' => 1];
            $res = RepairstoreGoodsRepository::api_get_list($option);
            $res = list_page_data($res);

            $list = [];
            if ($res['data']) {
                foreach ($res['data'] as $key => $value) {
                    $list['list'][] = [
                        'id' => $value['id'],
                        'img' => reset($value['pic'])['picurl']['full_src'],
                        'name' => $value['name'],
                        'price' => $value['price']
                    ];
                }
            }
            $list['page'] = $res['page_data'];

            return hello_success('查询成功', $list);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 获取维修服务商品详情（服务）
     *
     * 2019 12 16
     */
    public function get_repair_goods_detail($arr_input)
    {
        try {
            $n_id = intval($arr_input['id']);
            if ($n_id == 0) {
                return hello_error('商品ID不能为空');
            }

            //查询
            $arr_option['with'] = ['shop' => function ($query) {
                $query->with(['area_name']);
            }];
            $result = RepairstoreGoodsRepository::get_one($n_id, $arr_option);

            if ($result->first()) {
                $res = $result->toArray();
                $is_collect = false;

                if (!empty($arr_input['user_id'])) {
                    $arr_where = ['x_id' => $n_id, 'user_id' => $arr_input['user_id'], 'type' => 2];
                    $count = CollectRepository::get_count_by_where((array)$arr_where);
                    if ($count > 0) {
                        $is_collect = true;
                    }
                }

                $http = env('API_HOST', '');
                if (stripos($res['detail'], '<img src="/')) {
                    $res['detail'] = str_replace('src="/', 'src="' . $http . '/', $res['detail']);
                }

                /* if (stripos($res['detail'], '<img src="')) {
                     $res['detail'] = str_replace('/>', ' align="center" width="100%"/>', $res['detail']);
                 }*/
                $pic = [];
                foreach ($res['pic'] as $item) {
                    $pic[] = $item['picurl']['full_src'];
                }

                $city = str_replace(',', '', $res['shop']['area_name']['mername']);
                $detail = [
                    'id' => $res['id'],
                    'banner' => $pic,
                    'name' => $res['name'],
                    'shop_id' => $res['shop']['id'],
                    'title' => $res['shop']['name'],
                    'shop_address' => $city . $res['shop']['address'],
                    'price' => $res['price'],
                    'detail' => $res['detail'],
                    'serve' => $res['fuwu'],
                    'price_indication' => $res['price_indication'],
                    'is_collect' => $is_collect,
                ];
                return hello_success('查询成功', $detail);
            } else {
                return hello_error('商品不存在');
            }

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     *  选择服务后预生成订单（服务）
     *
     *  2019 12 09
     */
    public function repair_order_preview($arr_input)
    {
        try {
            if (empty($arr_input['repair_id'])) {
                return hello_error('服务种类id不能为空');
            }
            $repair_id = intval($arr_input['repair_id']);
            $res = RepairstoreGoodsRepository::get_one($repair_id)->toarray();//查询
            if ($res) {
                $arrInput = ['with' => ['area_name'], 'where' => ['id' => $res['repairstore_id']]];
                $shop_obj = ShopRepository::get_one($arrInput);//获取门店信息
                if ($shop_obj->first()) {
                    $coordinate = [
                        'start_longitude' => $arr_input['lon'],
                        'start_latitude' => $arr_input['lat'],
                        'end_longitude' => $shop_obj->longitude,
                        'end_latitude' => $shop_obj->latitude,
                    ];

                    //重新计算距离
                    $distance = CommonService::api_location_distance($coordinate);

                    $city = str_replace(',', '', $shop_obj->area_name['mername']);
                    $data['shop_name'] = $shop_obj->name;
                    $data['shop_type'] = $shop_obj->shop_type;
                    $data['shop_address'] = $city . $shop_obj->address;
                    $data['distance'] = $distance['state'] == 0 ? $distance['data']['en_default'] : '0.00 km';
                } else {
                    return hello_error('门店不存在');
                }

                $data['user_realname'] = $arr_input['user_realname'];
                $data['user_phone'] = $arr_input['user_phone'];
                $data['repair_goods_id'] = $res['id'];
                $data['repair_name'] = $res['name'];
                $data['total_price'] = $res['price'];

                foreach ($res['pic'] as $key => $value) {
                    $data['pic'][] = $value['picurl']['full_src'];
                }
            } else {
                return hello_error('查询失败');
            }

            return hello_success('查询成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 生成服务订单（服务）
     *
     * 2019 12 10
     */
    public function generate_repair_order($arr_input)
    {
        try {
            if (empty($arr_input['repair_goods_id'])) {
                return hello_error('服务商品id不能为空');
            }

            $goods_id = intval($arr_input['repair_goods_id']);
            //获取服务商商品信息
            $goods = RepairstoreGoodsRepository::get_goods_price($goods_id);//获取商品价格
            if ($goods->first()) {

                //优惠金额计算
                $coupon_price = 0.00;
                if (!empty($arr_input['coupons_id']) && !empty($arr_input['user_coupons_id'])) {
                    $coupons_array = ['type' => 1, 'order_amount' => $goods->price, 'coupon_id' => $arr_input['coupons_id']];
                    $coupon = PublicService::order_imputed_price((array)$coupons_array);

                    if ($coupon['state'] == 0) {
                        $coupon_price = $coupon['data']['coupon_price'];
                    } else {
                        return $coupon;
                    }
                }

                $pay_price = $goods->price - $coupon_price;//实际应该支付的金额
                if ((float)$arr_input['pay_amount'] != $pay_price) {
                    return hello_error('实际支付金额有误，订单创建失败');
                }

                $order_data['order_type'] = 1;
                $order_data['goods_type'] = $goods->type;
                $order_data['goods_name'] = $goods->name;
                $order_data['order_price'] = $goods->price;
                $order_data['order_number'] = random_order_sn('WXFW');
                $order_data['shop_id'] = $goods->repairstore_id;
                $order_data['user_id'] = $arr_input['user_id'];
                $order_data['repairstore_goods_id'] = $goods_id;
                $order_data['coupons_id'] = $arr_input['coupons_id'];
                $order_data['user_coupons_id'] = $arr_input['user_coupons_id'];
                $order_data['coupon_price'] = $coupon_price;
                $order_data['pay_price'] = $pay_price;
                $order_data['is_online_pay'] = $arr_input['is_online_pay'];

                $res = OrderRepairstoreRepository::add_one($order_data);

                $result = ['order_id' => $res->id];

                return hello_success('服务订单创建成功', $result);
            } else {
                return hello_error('商品不存在');
            }

            return hello_error('订单创建失败');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 生成保养订单（保养）
     *
     * 2019 12 10
     */
    public function generate_maintain_order($arr_input)
    {
        try {
            if (empty($arr_input['maintain_shop_id'])) {
                return hello_error('保养种类id不能为空');
            }
            $maintain_id = intval($arr_input['maintain_shop_id']);
            //查询
            $arr_option['with'] = ['maintain_shop_goods', 'son_config'];
            $maintain_obj = MaintainShopRepository::get_one($maintain_id, $arr_option);

            if ($maintain_obj->first()) {
                $maintain = $maintain_obj->toarray();
                $total_price = 0.00;
                foreach ($maintain['maintain_shop_goods'] as $key => $value) {
                    //计算商品总金额
                    $total_price += $value['product']['price'] * $value['num'];
                    //库存验证
                    if ($value['num'] > $value['product']['stock']) {
                        return hello_error($value['goods']['name'] . '【库存不足】');
                    }
                }

                //优惠金额计算
                $coupon_price = 0.00;
                if (!empty($arr_input['coupons_id']) && !empty($arr_input['user_coupons_id'])) {
                    $coupons_array = ['type' => 1, 'order_amount' => $total_price, 'coupon_id' => $arr_input['coupons_id']];
                    $coupon = PublicService::order_imputed_price((array)$coupons_array);

                    if ($coupon['state'] == 0) {
                        $coupon_price = $coupon['data']['coupon_price'];
                    } else {
                        return $coupon;
                    }
                }

                $pay_price = $total_price - $coupon_price;//实际应该支付的金额
                if ((float)$arr_input['pay_amount'] != $pay_price) {
                    return hello_error('实际支付金额有误，订单创建失败');
                }

                $order_data['order_type'] = 2;
                $order_data['maintain_shop_id'] = $maintain_id; //$maintain['son_config']['id'];
                //$order_data['goods_name'] = $maintain['son_config']['name'];
                $order_data['goods_name'] = $maintain['custom_title'] ?? $maintain['son_config']['name'];
                $order_data['order_price'] = $total_price;
                $order_data['order_number'] = random_order_sn('WXBY');
                $order_data['shop_id'] = $maintain['shop_id'];
                $order_data['user_id'] = $arr_input['user_id'];
                $order_data['coupon_price'] = $coupon_price;
                $order_data['goods_num'] = count($maintain['maintain_shop_goods']);
                $order_data['coupons_id'] = $arr_input['coupons_id'];
                $order_data['user_coupons_id'] = $arr_input['user_coupons_id'];
                $order_data['pay_price'] = $pay_price;
                $order_data['is_online_pay'] = $arr_input['is_online_pay'];

                $res = OrderRepairstoreRepository::add_one($order_data); //生成主表订单数据

                $goods = [];
                foreach ($maintain['maintain_shop_goods'] as $key => $value) {
                    $goods[] = [
                        'order_repairstore_id' => $res['id'],
                        'goods_id' => $value['goods_id'],
                        'product_id' => $value['product']['id'],
                        'goods_price' => $value['product']['price'],
                        'goods_num' => $value['num'],
                        'goods_amount' => $value['num'] * $value['product']['price'],
                    ];
                    //扣除商品库存
                    GoodsProductRepository::decrease_num($value['product']['id'], 'stock', $value['num']);
                }
                OrderRepairstoreGoodsRepository::add_many($goods);//将商品数据存入副表
                $result = [
                    'order_id' => $res->id,
                    'order_number' => $res->order_number,
                    'order_price' => number_format_money($res->order_price),
                    'need_pay_price' => number_format_money($res->pay_price)
                ];
                return hello_success('服务订单创建成功', $result);
            } else {
                return hello_error('商品不存在');
            }

            return hello_error('订单创建失败');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 支付订单
     *
     * 2019 12 10
     */
    public function repair_pay_order($arr_input)
    {
        try {
            if (empty($arr_input['order_id'])) {
                return hello_error('订单id不能为空');
            }
            if (empty($arr_input['order_number'])) {
                return hello_error('订单编号不能为空');
            }
            if (empty($arr_input['pay_amount'])) {
                return hello_error('实付金额不能为空');
            }

            $map = [
                'id' => $arr_input['order_id'],
                'order_number' => $arr_input['order_number'],
                'user_id' => $arr_input['user_id'],
                'status' => 0,
                'pay_status' => 0,
            ];
            //支付金额验证
            $order_obj = OrderRepairstoreRepository::find_one($map);
            if ($order_obj) {
                $order_array = $order_obj->toArray();//订单详情数组
                //支付金额验证（待）

                if ((float)$arr_input['pay_amount'] != $order_array['pay_price']) {
                    return hello_error('实际支付金额有误，订单支付失败');
                }

                if ((int)$arr_input['pay_type'] == 1) { //微信支付

                    self::pay_xin_order();

                } elseif ((int)$arr_input['pay_type'] == 2) {//支付宝支付

                    self::pay_bao_order();

                } else {
                    return hello_error('支付方式有误');
                }

            } else {
                return hello_error('订单不存在或订单状态有误，请重新下单');
            }

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 获取订单列表（保养，服务）
     *
     * 2019 12 12
     */
    public function get_repair_store_order($arr_input)
    {
        try {
            $status = intval($arr_input['status']);
            $where = [];
            if ($status == 1) {//待支付
                $where['pay_status'] = '0';
                $where['status'] = '0';
            } elseif ($status == 2) {//待检修
                $where['pay_status'] = '1';
                $where['status'] = '0';
            } elseif ($status == 3) {//待评价
                $where['pay_status'] = '1';
                $where['status'] = '5';
            }

            $arr_option['where'] = ['user_id' => $arr_input['user_id']];
            $arr_option['with'] = ['shop', 'repair_goods_pic' /* ,'goods'*/];

            $listAll = OrderRepairstoreRepository::api_get_list($arr_option, $where);
            $data = list_page_data($listAll);

            $list = self::data_collation($data['data']);

            $res = ['list' => $list, 'page' => $data['page_data']];
            return hello_success('ok', $res);

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 订单数据整理
     */
    public function data_collation(array $data)
    {
        $list = [];
        foreach ($data as $key => $item) {

            if ($item['is_online_pay'] == 1 && $item['status'] == 0) {
                $order_status = '待处理';
            } else {
                $order_status = OrderRepairstoreRepository::orderStatus($item['status'], $item['pay_status']);
            }
            if ($item['order_type'] == 1) {
                $pic_url = $item['repair_goods_pic']['picurl']['full_src'];
            } else {
                $pic_url = $item['shop']['logo']['full_src'];
            }

            $list[] = [
                'order_type' => $item['order_type'],
                'order_id' => $item['id'],
                'order_number' => $item['order_number'],
                'shop_id' => $item['shop']['id'],
                'shop_name' => $item['shop']['name'],
                'order_name' => $item['goods_name'],
                'created_at' => $item['created_at'],
                'order_price' => $item['order_price'],
                'need_pay_price' => $item['pay_price'],
                'pay_status' => $item['pay_status'],
                'status' => $item['status'],
                'is_online_pay' => $item['is_online_pay'],
                'order_status' => $order_status,
                'pic_url' => $pic_url
            ];
        }

        return $list;
    }

    /**
     * 获取订单详情（保养，服务）
     *
     * 2019 12 12
     */
    public function get_repair_store_order_info($arr_input)
    {
        try {
            $order_id = intval($arr_input['order_id']);

            if (empty($order_id)) {
                return hello_error('订单id不能为空');
            }

            if (empty($arr_input['lon']) || empty($arr_input['lat'])) {
                return hello_error('经度或纬度不能为空');
            }

            $arr_option['with'] = ['maintain_goods',
                'shop' => function ($query) {
                    $query->with(['area_name']);
                }, 'repair_goods_pic'];
            $detail_obj = OrderRepairstoreRepository::get_one($order_id, $arr_option);

            if ($detail_obj->first()) {
                $detail_array = $detail_obj->toArray();

                $city = str_replace(',', '', $detail_array['shop']['area_name']['mername']);

                if ($detail_array['order_type'] == 2 && !empty($detail_array['maintain_goods'])) {//保养订单
                    foreach ($detail_array['maintain_goods'] as $ky => $val) {
                        $maintain_goods['list'][] = [
                            'goods_id' => $val['goods_id'],
                            'goods_name' => $val['get_goods']['name'],
                            'goods_num' => $val['goods_num'],
                            'goods_price' => $val['goods_price'],
                            'goods_pic' => $val['get_product']['pic']['full_src'],
                            //'product_id' => $val['product_id'],
                            'product_specs' => $val['get_product']['specs']['name'],
                        ];
                    }
                } else {//服务订单
                    $repair_goods = [
                        'goods_id' => $detail_array['repairstore_goods_id'],
                        'goods_pic' => $detail_array['repair_goods_pic']['picurl']['full_src'],
                        'goods_num' => $detail_array['goods_num'],
                        'goods_price' => $detail_array['order_price'],
                    ];
                }

                if ($detail_array['is_online_pay'] == 1 && $detail_array['status'] == 0) {
                    $order_status = '待处理';
                } else {
                    $order_status = OrderRepairstoreRepository::orderStatus($detail_array['status'], $detail_array['pay_status']);
                }

                $coordinate = [
                    'start_longitude' => $arr_input['lon'],
                    'start_latitude' => $arr_input['lat'],
                    'end_longitude' => $detail_array['shop']['longitude'],
                    'end_latitude' => $detail_array['shop']['latitude']
                ];

                //计算距离
                $distance = CommonService::api_location_distance($coordinate);

                $detail_array['order_status'] = $order_status;
                $detail_array['shop_id'] = $detail_array['shop']['id'];
                $detail_array['shop_name'] = $detail_array['shop']['name'];
                $detail_array['shop_phone'] = $detail_array['shop']['phone'];
                $detail_array['shop_address'] = $city . $detail_array['shop']['address'];
                $detail_array['shop_lon'] = $detail_array['shop']['longitude'];
                $detail_array['shop_lat'] = $detail_array['shop']['latitude'];
                $detail_array['distance'] = $distance['state'] == 0 ? $distance['data']['en_default'] : '0.00 km';
                $detail_array['pic_url'] = $detail_array['shop']['logo']['full_src'];
                $detail_array['maintain_goods'] = $maintain_goods ?? null;//保养订单中的商品数组
                $detail_array['repair_goods'] = $repair_goods ?? null;//服务订单商品信息;

                unset($detail_array['shop']);
                unset($detail_array['repair_goods_pic']);
                return hello_success('ok', $detail_array);
            }

            return hello_error('订单不存在');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 修改订单状态（取消订单，申请退款）
     *
     * 2019 12 13
     */
    public function handle_repair_order($arr_input)
    {
        try {
            if (empty($arr_input['order_id'])) {
                return hello_error('订单id不能为空');
            }

            $map = ['id' => $arr_input['order_id'], 'user_id' => $arr_input['user_id'],];
            $order = OrderRepairstoreRepository::find_one($map);
            if ($order) {

                if ((int)$arr_input['status'] == 1) { //取消订单
                    if (empty($arr_input['reason'])) {
                        return hello_error('取消原因必填');
                    }
                    if ($order->pay_status == 0 && $order->status == 0) {
                        $upData = ['status' => 2, 'cancel_reason' => $arr_input['reason'], 'cancel_time' => date('Y-m-d H:i:s')];
                        if (OrderRepairstoreRepository::edit_pay_status($map, $upData)) {

                            //回收商品库存
                            self::backStock($arr_input['order_id']);

                            return hello_success('订单取消成功！');
                        } else {
                            return hello_error('订单取消失败');
                        }
                    } else {
                        return hello_error('订单状态不对，取消失败！');
                    }


                } elseif ((int)$arr_input['status'] == 2) {//申请退款

                    if (empty($arr_input['reason'])) {
                        return hello_error('申请退款原因必填');
                    }
                    if (in_array($order->pay_status, [1, 4]) && $order->status == 0) {
                        $upData = ['pay_status' => 2, 'refund_cause' => $arr_input['reason'], 'apply_refund_time' => date('Y-m-d H:i:s')];
                        if (OrderRepairstoreRepository::edit_pay_status($map, $upData)) {
                            return hello_success('已发送退款申请，等待管理人员审核！');
                        } else {
                            return hello_error('申请失败！请联系商家');
                        }
                    } else {
                        return hello_error('订单状态不对，申请失败！');
                    }


                } elseif ((int)$arr_input['status'] == 3) {//用户确认完成
                    if ($order->status == 1) {
                        $upData = ['status' => 5, 'is_finish' => 1];
                        if (OrderRepairstoreRepository::edit_pay_status($map, $upData)) {
                            return hello_success('操作成功！');
                        } else {
                            return hello_error('操作失败');
                        }
                    } else {
                        return hello_error('订单状态不对，操作失败！');
                    }


                } else {
                    return hello_error('操作状态有误');
                }

            } else {
                return hello_error('订单不存');
            }

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     *保养订单取消订单回收库存
     */
    public function backStock($order_id)
    {
        $arr_option['with'] = ['maintain_goods'];
        $arr_option['field'] = ['id'];
        $detail_obj = OrderRepairstoreRepository::get_one($order_id, $arr_option);

        if ($detail_obj->first() && $detail_obj->maintain_goods) {
            foreach ($detail_obj->maintain_goods as $item) {
                GoodsProductRepository::increase_num($item->product_id, 'stock', $item->goods_num);
            }
        }
    }

    /**
     * 删除订单
     *
     * 2019 12 13
     */
    public function del_order($arr_input)
    {
        try {
            if (empty($arr_input['order_id'])) {
                return hello_error('订单id不能为空');
            }

            $map = [
                'id' => intval($arr_input['order_id']),
                'user_id' => $arr_input['user_id']
            ];

            $res = OrderRepairstoreRepository::delete_by_where($map);
            if ($res === false) {
                return hello_error('删除失败');
            }
            return hello_success('删除成功');

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 获取售后订单列表
     */
    public function get_sale_order(array $arr_input)
    {
        try {

            $arr_option['where'] = ['user_id' => $arr_input['user_id']];
            $arr_option['with'] = ['shop', 'maintain_goods', 'repair_goods_pic'];
            $listAll = OrderRepairstoreRepository::get_sale_order($arr_option);
            $data = list_page_data($listAll);

            $list = self::data_collation($data['data']);

            $res = ['list' => $list, 'page' => $data['page_data']];

            return hello_success('获取成功', $res);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }


    /**
     * 支付前-检查订单
     */
    public function check_wxfw_pay_order_api($n_id, $n_uid)
    {
        try {
            if ($n_id <= 0) {
                return hello_error('数据id不能为空');
            }
            if ($n_uid <= 0) {
                return hello_error('用户id不能为空');
            }

            //查询订单信息
            $map = ['id' => $n_id, 'user_id' => $n_uid, 'pay_status' => 0, 'status' => 0];
            $order_obj = OrderRepairstoreRepository::get_one_by_where($map);

            if ($order_obj->first()) {
                $order_array = $order_obj->toArray();//订单详情数组
                $arr_data = [
                    'out_trade_no' => $order_array['order_number'],
                    'total_fee' => $order_array['pay_price'] * 100// **单位：分**
                ];

                return hello_success('成功', $arr_data);
            }

            return hello_error('该订单不存在或无效，请重新下单');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 支付回调-订单处理
     */
    public function notify_for_wxfw($s_order_sn, $s_transaction_id = '', $s_pay_time = '')
    {
        //订单状态修改
        $arr_where = ['order_number' => $s_order_sn];
        $arr_data = [
            'pay_status' => 1,
            'pay_type' => 2,
            'pay_time' => $s_pay_time,
        ];

        $res = OrderRepairstoreRepository::edit_pay_status($arr_where, $arr_data);

        if ($res == 1) {
            return hello_success('成功');
        }
        return hello_error('确认失败', [], '订单状态修改失败');
    }

    /**
     * 支付完成后-查询订单
     */
    public function order_result_for_wxfw($n_id)
    {
        try {
            if ($n_id <= 0) {
                return hello_error('数据id不能为空');
            }
            $arr_option = [
                'field' => ['id', 'pay_status']
            ];
            $result = OrderRepairstoreRepository::get_one_by_where(['id' => $n_id], $arr_option);
            if (is_null($result)) {
                return hello_error('数据不存在');
            }

            $result = [
                'id' => $result->id,
                'pay_state' => intval($result->pay_status) + 1,
            ];

            return hello_success('成功', $result);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

}